package com.gx.security.digital_signature;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import java.security.*;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by gx on 2017/3/30.
 */
public class DSATest {
    private static final String src = "imooc security signatureRSA";

    public static void main(String[] args) {
        jdkDSA();
    }

    public static void jdkDSA() {
        //初始化秘钥
        KeyPairGenerator keyPairGenerator = null;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("DSA");

            //初始化长度
            keyPairGenerator.initialize(512,new SecureRandom());
//            keyPairGenerator.initialize(1024, new SecureRandom());
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            //公钥验证
            DSAPublicKey dsaPublicKey = (DSAPublicKey) keyPair.getPublic();
            //私钥签名
            DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) keyPair.getPrivate();
            System.out.println("Public Key:" + Base64.encodeBase64String(dsaPublicKey.getEncoded()));
            System.out.println("PrivateKey :" + Base64.encodeBase64String(dsaPrivateKey.getEncoded()));


            //执行签名
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("DSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initSign(privateKey);
            //输入执行加密的内容
            signature.update(src.getBytes());



            //获得签名
            byte [] result  = signature.sign();
            System.out.println("JDK RSA sign 实现"+ Hex.encodeHexString(result));


            //验证签名
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("DSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            //得到签名
            signature = Signature.getInstance("SHA1withDSA");
            signature.initVerify(publicKey);
            signature.update(src.getBytes());
            boolean bool = signature.verify(result);
            System.out.println("RSA 验证结果——-->"+bool);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
